﻿using System.Linq;
using System.Security.Authentication;
using System.Threading.Tasks;
using AutoMapper;
using IdentityModel;
using IdentityModel.Client;
using K9Nano.Application;
using K9Nano.Authentication;
using K9Nano.Dependency;
using K9Nano.Domain;
using K9Nano.Runtime;
using K9Nano.Share;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;

namespace K9Nano.IdentityServerCore.Account
{
    public class AccountAppService<TUser>: ApplicationService where TUser: User
    {
        protected readonly UserManager<TUser> UserManager;

        public AccountAppService(IUnitOfWork uow, IMapper mapper, ISessionContext sessionContext, ILoggerFactory loggerFactory, UserManager<TUser> userManager) : base(uow, mapper, sessionContext, loggerFactory)
        {
            UserManager = userManager;
        }

        public virtual async ValueTask<UserInfoDto> GetUserInfo()
        {
            if (SessionContext.UserId == null) return new UserInfoDto();

            var user = await UserManager.FindByIdAsync(SessionContext.UserId.Value.ToString());

            if(user == null) throw new AuthenticationException();

            var claims = await UserManager.GetClaimsAsync(user);
            // todo Cache ?
            return new UserInfoDto
            {
                Sub = SessionContext.UserId.ToString(),
                Name = claims.FirstOrDefault(x=>x.Type == K9SharedConstants.NameClaimType)?.Value,
                Avatar = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Profile)?.Value,
                Email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value,
            };
        }
    }
}